package com.googlecode.droidircclient.Sockets;
/* =================================================
 * Droid IRC Client
 * Authors: Kevin Garton, Dennis McWherter
 * 9 September 2011
 * =================================================*/

import java.net.*;
import java.io.*;

public class ClientSocket {
	private Socket Sock;
	private InputStream IStream;
	private InputStreamReader ISReader;
	private BufferedReader In;
	private OutputStream Out;
	private boolean IsValid;
	
	/**
	 * SocketBase
	 * Attempts to initialize a socket
	 * 
	 * @param host
	 * @param port
	 * @throws IOException
	 */
	public ClientSocket(String host, int port) throws IOException {
		try {
			Sock = new Socket(host, port);
		} catch(IOException e) {
			throw e;
		}
		IStream  = Sock.getInputStream();
		ISReader = new InputStreamReader(IStream);
		In  = new BufferedReader(ISReader);
		Out = Sock.getOutputStream();
		IsValid = true;
	}
	
	/**
	 * close
	 * Try to close the socket
	 */
	public void close() {
		if(Sock == null)
			return;
		try {
			In.close();
			ISReader.close();
			IStream.close();
			Out.close();
			Sock.close();
		} catch(IOException e) {
			System.err.println("Exception Caught: "+e.toString());
		}
		IsValid = false;
	}
	
	/**
	 * write
	 * Attempt to write data to an open socket connection
	 * 
	 * @param data
	 */
	public void write(String data) {
		try {
			Out.write(data.getBytes());
		} catch(IOException e) {
			/* Die silently - maybe print out the debug info */
			System.err.println("Exception Caught: "+e.toString());
		}
	}
	
	/**
	 * read
	 * Attempt to read from an open socket connection
	 * 
	 * @return string
	 */
	public String read() {
		if(Sock.isClosed() || !IsValid)
			return new String();
		String ret = null;
		try {
			ret = In.readLine();
		} catch(IOException e) {
			/* Die silently */
			System.err.println("Exception Caught: "+e.toString());
		}
		return ret;
	}
	
	/**
	 * isValid
	 * Return whether or not the socket is still valid or not
	 * 
	 * @return boolean (true if valid, false otherwise)
	 */
	public boolean isValid() {
		return IsValid;
	}
}
